<?php

namespace App\Repositories\Cache;

use Illuminate\Support\Facades\Cache;

class RegisterCode
{
    private $codeCacheKey = "register_code_";
    private $sendNumCacheKey = "register_code_send_num_";
    private $codeTtl = 2*60*60;
    private $sendTimesTtl = 24*60*60;
    private $overrunTimes = 10;

    /**
     * 获取验证码
     *
     * @param string $mark
     * @return mixed
     */
    public function getCode(string $mark)
    {
        $key = $this->makeCodeCacheKey($mark);
        return Cache::get($key);
    }

    /**
     * 设置注册验证码缓存
     *
     * @param string $mark
     * @param $code
     * @param int $ttl
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *
     * @return boolean
     */
    public function setCodeCache(string $mark, $code, $ttl = 0)
    {
        $ttl = $ttl ?: $this->codeTtl;
        $key = $this->makeCodeCacheKey($mark);
        Cache::set($key, $code, $ttl);
        return true;
    }

    /**
     * 设置注册验证码发送次数缓存
     *
     * @param string $mark
     * @return bool
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function setSendTimesCache(string $mark)
    {
        $key = $this->makeSendNumKey($mark);
        if (! Cache::get($key)) {
            Cache::set($key, 1, $this->sendTimesTtl);
        } else {
            Cache::increment($key);
        }

        return true;
    }

    /**
     * 检测缓存次数是否超限
     *
     * @param string $mark
     * @param int $overrunTimes
     *
     * @return bool
     */
    public function check(string $mark, int $overrunTimes = 0)
    {
        $overrunTimes = $overrunTimes != 0 ? $overrunTimes : $this->overrunTimes;
        $key = $this->makeSendNumKey($mark);

        return Cache::get($key) < $overrunTimes;
    }

    /**
     * 生成一个验证码缓存键名
     *
     * @param $mark
     * @return string
     */
    private function makeCodeCacheKey($mark)
    {
        return $this->codeCacheKey . $mark;
    }

    /**
     * 生成一个验证码发送次数缓存键名
     *
     * @param $mark
     * @return string
     */
    private function makeSendNumKey($mark)
    {
        return $this->sendNumCacheKey . $mark;
    }
}